package org.batyrov.equery.server;

import java.net.Socket;
import java.io.*;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by IntelliJ IDEA.
 * User: admin
 * Date: 12.09.2009
 * Time: 19:36:38
 * To change this template use File | Settings | File Templates.
 */
public class SocketProcessor{
    Socket _socket;
    BufferedReader socketReader;
    BufferedWriter socketWriter;
    String str;
    InReader inReader;


    SocketProcessor(Socket socketParam) throws IOException {
        _socket = socketParam;
        socketReader = new BufferedReader(new InputStreamReader(_socket.getInputStream(), "windows-1251"));
        socketWriter = new BufferedWriter(new OutputStreamWriter(_socket.getOutputStream(), "windows-1251"));
        if (!registerClient()) {
            throw new IOException();
        }
        System.out.println("client in equery");
        inReader = new InReader(socketReader, _socket);
        inReader.start();
    }

    public boolean registerClient() throws IOException {
        if (socketReader.readLine().equals("Salam")) {
            send("Vaaleikum");
            if (socketReader.readLine().equals("HAY"))
                return true;
        }
        System.out.println("Register successfull");
        return false;
    }

    public void send(String line) {
        try {
            socketWriter.write(line);
            socketWriter.write("\n");
            socketWriter.flush();
        } catch (IOException e) {
            close();
        }
    }

    public synchronized void close(){
        if (!_socket.isClosed()) {
            try {
                socketReader.close();
                System.out.println("socketReader close");
                inReader.close();
                System.out.println("inReader close");
                _socket.close();
                System.out.println("_socket close");
            } catch (IOException ignored) {
                ignored.printStackTrace();
            }
        }
    }
}